package com.sentry.commons.http;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
 * 支持UTF8和GBK两种字符集方式
 * @author WuBo (wub1@minshenglife.com)
 *
 */
public class CharsetResponseHandler implements ResponseHandler<String> {
    
    private static final Charset CHARSET_GBK = Charset.forName("GBK");

    public static final ResponseHandler<String> UTF8 = new CharsetResponseHandler(Consts.UTF_8);
    
    public static final ResponseHandler<String> GBK = new CharsetResponseHandler(CHARSET_GBK);
    
    
    public static final Map<Charset,ResponseHandler<String>> HANDLERS = new HashMap<Charset, ResponseHandler<String>>(2);
    
    static{
        HANDLERS.put(Consts.UTF_8, UTF8);
        HANDLERS.put(CHARSET_GBK, GBK);
    }
    
    
    private Charset charset = Consts.UTF_8;
    
    
    private CharsetResponseHandler(Charset cs){
        this.charset = cs;
    }
    

    public String handleResponse(final HttpResponse response)
            throws HttpResponseException, IOException {
        final StatusLine statusLine = response.getStatusLine();
        final HttpEntity entity = response.getEntity();
        if (statusLine.getStatusCode() >= 300) {
            EntityUtils.consume(entity);
            throw new HttpResponseException(statusLine.getStatusCode(),
                    statusLine.getReasonPhrase());
        }
        return entity == null ? null : EntityUtils.toString(entity, charset);
    }

}
